package com.qinglei.recoup.system.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qinglei.recoup.common.domain.*;
import com.qinglei.recoup.system.domain.Bed;
import com.qinglei.recoup.system.service.BedService;
import com.qinglei.recoup.system.service.RadarService;
import com.qinglei.recoup.system.service.RadarUserDataFourService;
import com.qinglei.recoup.system.service.RadarUserDataService;
import com.qinglei.recoup.system.util.ProducerInstance;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Slf4j
@Component
@RabbitListener(queues = CommonConstant.MQ_RADAR_DATA_QUEUE, concurrency = "4")
public class RadarDataMessageConsumer {
    @Resource
    private RadarUserDataService radarUserDataService;

    @Resource
    private RadarService radarService;

    @Resource
    private BedService bedService;

    @Resource
    private RadarUserDataFourService radarUserDataFourService;

    @Resource
    private BreathHeartAlarmV3 breathHeartAlarmV3;

    @Resource
    private BreathHeartAlarmV4 breathHeartAlarmV4;

    @Value("${Health.onOrOffV3}")
    private boolean onOrOffV3;
    @Value("${device-event-topic}")
    private String deviceTopic;
    @Value("${rocketmq.name-server}")
    private String rocketServer;
    @Value("${ql-device-event-topic}")
    private String qlDeviceEventTopic;
    @Value("${ql-device-event-group}")
    private String qlDeviceEventGroup;
    @Value("${device-event-group}")
    private String deviceGroup;


    public void Test(String sn, Integer devStatus) {
        try {
            JSONObject deviceInfo = new JSONObject();
            deviceInfo.put("deviceSn", sn);
            deviceInfo.put("deviceStatus", devStatus);

            log.info("测试 设备上下线消息: sn:【{}】, 状态:【{}】", sn, devStatus);

            MQProducer realDataProducer = ProducerInstance.getProducerInstance().getInstance(rocketServer, qlDeviceEventGroup);
            Message realDataMsg = new Message(qlDeviceEventTopic, deviceInfo.toString().getBytes(StandardCharsets.UTF_8));
            realDataProducer.sendOneway(realDataMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RabbitHandler
    public void process(RadarMessage message) {
        if (DateUtil.now().endsWith("00")) {
            // 每分钟 打印一次
            log.info("接收到设备实时数据: 设备snCode:【{}】, 协议版本:【{}】, 消息类型:【{}】,  数据:【{}】",
                    message.getSn(), message.getProCode(), message.getType(), message.getData());
        }

        /* *************** 推送利剑 设备的上下线消息 ************* */
        //设备状态 消息
        if (message.getType() == RadarMessage.TYPE_DEVICE_STATUS) {
            log.info("接收到设备上下线消息: 设备snCode:【{}】, 协议版本:【{}】, 消息类型:【{}】,  数据:【{}】",
                    message.getSn(), message.getProCode(), message.getType(), message.getData());
            try {
                String sn = message.getSn();
                Object data = message.getData();
                IotRadarStatusData iotRadarStatusData = null;
                try {
                    iotRadarStatusData = (IotRadarStatusData) data;
                } catch (Exception e) {
                    log.error("上下线消息类型转换异常!!");
                    e.printStackTrace();
                }
                String status = JSONUtil.parseObj(data).getStr("status");
                int devStatus;
                if (CharSequenceUtil.equals(status, "online")) {
                    devStatus = 0;
                } else if (CharSequenceUtil.equals(status, "offline")) {
                    devStatus = 1;
                } else {
                    devStatus = -1;
                }
                JSONObject deviceInfo = new JSONObject();
                deviceInfo.put("deviceSn", sn);
                deviceInfo.put("deviceStatus", devStatus);
                deviceInfo.put("data", iotRadarStatusData);
                log.info("设备状态消息: sn:【{}】, 状态:【{}】", sn, devStatus);
                MQProducer realDataProducer = ProducerInstance.getProducerInstance().getInstance(rocketServer, qlDeviceEventGroup);
                Message realDataMsg = new Message(qlDeviceEventTopic, deviceInfo.toString().getBytes(StandardCharsets.UTF_8));
                realDataProducer.sendOneway(realDataMsg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //用户数据 消息
        if (message.getType() == RadarMessage.TYPE_USER_DATA) {
            try {
                if (DateUtil.now().endsWith("00")) {
                    log.info("开始插入用户上传数据!!!");
                }
                RadarUserDataFour radarUserDataFour = (RadarUserDataFour) message.getData();
                radarUserDataFour.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                radarUserDataFourService.save(radarUserDataFour);
                if (DateUtil.now().endsWith("00")) {
                    log.info("插入用户上传数据结束!!!");
                }
            } catch (Exception e) {
                log.error("插入数据异常!!!", message, e);
            }
            try {
                RadarUserDataFour radarUserDataFour = (RadarUserDataFour) message.getData();
                MQProducer realDataProducer = ProducerInstance.getProducerInstance().getInstance(rocketServer, deviceGroup);
                Message realDataMsg = new Message(deviceTopic, JSON.toJSONString(radarUserDataFour).getBytes(StandardCharsets.UTF_8));
                realDataProducer.sendOneway(realDataMsg);
            } catch (Exception e) {

                e.printStackTrace();
            }
        }

//        Date date = new Date();
//        date.setTime(message.getTimestamp());
//        log.info("------jssbscsj----" + JSON.toJSONString(message));
        // log.info("receive RadarMessage process:{}", JsonUtils.objectToJson(message));
        try {
            String proCode = message.getProCode();
            if (proCode == null) {
                //不解析没有协议号的数据
                return;
            }
            Bed bed = bedService.getBedBySn(message.getSn());
            if (bed != null) {
                if (!proCode.equals(bed.getRadarVersion())) {
                    UpdateWrapper<Bed> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", bed.getId());
                    Bed bedUpdate = new Bed();
                    bedUpdate.setRadarVersion(proCode);
                    bedService.getBaseMapper().update(bedUpdate, updateWrapper);
                }
            } else {
                //不解析未绑定床位的数据
                return;
            }
            if (RadarVersionEnum.VERSION_V3.getCode().equals(proCode)) {
                if (message.getType() == RadarMessage.TYPE_USER_DATA) {
                    RadarUserDataDTO data = (RadarUserDataDTO) message.getData();
                    // 去除翻身状态
                    if (data.getS2() > 3) {
                        return;
                    }
                    // 保存雷达上传的用户数据
                    radarUserDataService.saveRadarUserData(message);
                    // 更新雷达在线状态
                    radarService.updateOnlineStatus(message.getSn());
                    //更新呼吸过速、呼吸暂停状态
                    if (onOrOffV3) {
//                        breathHeartAlarmV3.updateBreathStatus(message);
                    }

                } else if (message.getType() == RadarMessage.TYPE_FALL_DOWN_DATA) {
                    // 更新雷达在线状态
                    radarService.updateOnlineStatusDownData(message.getSn());
                }
                // 处理雷达关联的床位状态   包含跌倒相关数据
                bedService.procRadarData(message, false);
            } else if (RadarVersionEnum.VERSION_V4.getCode().equals(proCode)) {
                radarUserDataFourService.saveRadarUserData(message);
                radarService.updateOnlineStatus(message.getSn());
                radarService.updateNetworkStatus(message.getSn());
                bedService.procRadarDataV4(message);
                breathHeartAlarmV4.updateBreathStatus(message);
            }
        } catch (Exception e) {
            log.error("process RadarMessage error RadarMessage:{}", message, e);
        }
    }

}
